package cn.veliger.springai.tools;

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.mozilla.universalchardet.UniversalDetector;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;


/**
 * 获取编码
 *
 * @author veliger
 * create on 2025-06-29
 **/
@Slf4j
@UtilityClass
public class CharsetDetector {
    /**
     * 获取编码
     *
     * @param inputStream
     * @return
     * @throws IOException
     */
    public String detectCharset(InputStream inputStream) {
        byte[] buf = new byte[4096];
        // 创建探测器
        UniversalDetector detector = new UniversalDetector(null);
        try (BufferedInputStream bis = new BufferedInputStream(inputStream)) {
            int nread;
            while ((nread = bis.read(buf)) > 0 && !detector.isDone()) {
                detector.handleData(buf, 0, nread);
            }
            // 通知探测器数据已经结束
            detector.dataEnd();
            return detector.getDetectedCharset();
        } catch (IOException e) {
            log.error("CharsetDetector.detectCharset error", e);
            return "";
        } finally {
            // 重置探测器，以便重用
            detector.reset();
        }
    }
}
